package swimv2gm.client.user;

import java.io.IOException;

import javax.naming.*;
import javax.servlet.http.*;

import swimv2gm.bl.session.*;

@SuppressWarnings("serial")
public class EditProfile extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
		doPost(request,response);
	}

	@Override
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
		UserManager man;
		try {
			man = (UserManager)InitialContext.doLookup("UserManager");
		} catch (NamingException e) {
			response.sendError(500);
			return;
		}
		Object uid_p = request.getSession().getAttribute("user");
		if (uid_p == null) {
			response.sendError(403);
			return;
		}
		long uid = -1;
		try {
			uid = (Long)uid_p;
		} catch (IllegalArgumentException e) {
			response.sendError(500);
			return;
		}
		boolean success = false;
		try {
			success = man.editProfile(uid,request.getParameter("email"),request.getParameter("nome"),
					request.getParameter("cognome"),request.getParameter("telefono"),request.getParameter("indirizzo"),
					request.getParameter("bio"),request.getParameter("password"),request.getParameter("newpassword"));
		} catch (ExistingDataException e) {
			response.sendRedirect("/SWIMv2gm/user/Profile?uid=" + uid + "&errortype=existing&action=edit");
			return;
		}

		if (success) {
			response.sendRedirect("/SWIMv2gm/user/Profile?uid=" + uid + "&edited=true");
		}
		else {
			response.sendRedirect("/SWIMv2gm/user/Profile?uid=" + uid + "&errortype=invalid&action=edit");
		}

	}
}
